#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/06/12 15:52
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：
import logging
import os
import sys
import re
from random import randint

import connect_database
import loadLog
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtWidgets import QTableWidgetItem
from pyqt5_common import show_message

from task_mapping_ui import Ui_Form
import timeEXT


class Window(QDialog):
    """docstring for Window"""
    # 任务配置
    task_config = {}
    select_table = None

    def __init__(self, local_connect, connect_dict):
        super(Window, self).__init__()
        self.local_connect = local_connect
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.log = logging.getLogger("main.Window")
        self.connect = connect_dict
        self.load_task_config()
        self.load_task_mapping()
        self.ui.source_table_list.activated.connect(lambda v: self.select_table_name(self.ui.source_table_list, v))
        self.ui.target_table_list.activated.connect(lambda v: self.select_table_name(self.ui.target_table_list, v))

    # 加载任务映射配置
    def load_task_mapping(self, task_name = None):
        if task_name:
            task_list = [task_name, ]
        else:
            task_list = [self.ui.task_field_group.itemText(i) for i in range(self.ui.task_field_group.count())]
        if not task_list:
            return
        for task_name in task_list:
            source_table, target_table, mode = task_name.split('>')
            task_config = self.get_task_config(task_name)
            field_config = self.get_field_config(source_table, target_table, mode)

            if not task_config or not field_config:
                self.log.warning("任务:{},任务配置或字段映射配置查询失败,不能初始化任务...")
                continue

            # 存储调度配置
            self.task_config.update({task_name: {}})

            row = task_config[0]
            source_gid_field = row['SerialField']
            self.task_config[task_name]['source_gid_field'] = source_gid_field
            flag_field = row['MarkField']
            flag_begin_value = row['MarkFieldInitValue']
            flag_end_value = row['MarkFieldEndValue']
            other = row['Other']
            datetime_field = row['DateField']
            source_connect = self.connect.get(row['SourceConnectName'])
            target_connect = self.connect.get(row['TagConnectName'])
            mode = int(mode)
            if not source_connect: continue
            source_type = source_connect.type.lower()
            if not target_connect: continue
            target_type = target_connect.type.lower()

            # 获取字段,组合字段
            name_list, source_field_list, target_field_list = self.get_field(field_config)
            source_field = ','.join(source_field_list)
            target_field = ','.join(target_field_list)

            # 目的字段类型
            field_type = self.get_field_info(target_connect, target_table, target_field_list)
            self.task_config[task_name]['field_type'] = field_type

            # 存储字段
            self.task_config[task_name]['name_list'] = name_list
            self.task_config[task_name]['source_field_list'] = source_field_list
            self.task_config[task_name]['target_field_list'] = target_field_list
            self.task_config[task_name]['source_gid_field'] = source_gid_field
            if source_gid_field not in source_field_list:
                self.log.warning("源主键流水字段：{}，不在映射表：{}内，请修改映射表".format(source_gid_field, source_field_list))
                return
            target_gid_field = target_field_list[source_field_list.index(source_gid_field)]
            self.task_config[task_name]['target_gid_field'] = target_gid_field
            self.task_config[task_name]['flag_field'] = flag_field
            self.task_config[task_name]['name'] = row['Description']

            # 组装查询语句
            sql = "SELECT {} FROM {} ".format(source_field, source_table)
            if flag_field:
                if source_type != 'access' and flag_begin_value.isdigit():
                    flag_begin_value = "'{}'".format(flag_begin_value)
                select_sql = "{} WHERE {}={} ".format(sql, flag_field, flag_begin_value)
            else:
                if source_type == 'access' and 'cstr' in source_gid_field.lower():
                    select_sql = "{} WHERE {}>'{}' ".format(sql, source_gid_field, '{}')
                else:
                    select_sql = "{} WHERE {}>{} ".format(sql, source_gid_field, '{}')

            if other:
                select_sql += "AND {} ".format(other)

            select_sql += "ORDER BY {}".format(source_gid_field)
            select_sql_ = self.get_select_count(select_sql, source_type)
            self.log.debug("初始化查询语句:{}".format(select_sql_))
            self.task_config[task_name]['select_sql'] = [select_sql_, source_connect]

            # 组装手工查询
            sql += "ORDER BY {}".format(source_gid_field)
            manual_select_sql = self.concat_manual_select(source_table, sql, other, datetime_field, source_connect.type)
            self.log.debug("初始化手动查询语句:{}".format(manual_select_sql))
            self.task_config[task_name]['manual_select_sql'] = [manual_select_sql, source_connect]

            # 组装执行语句

            # 插入或覆盖插入
            if mode in range(10):
                if mode > 4:
                    clear_sql = "DELETE FROM {} WHERE {} IN ({}) ".format(target_table, target_gid_field, '{}')
                else:
                    clear_sql = None
                self.task_config[task_name]['clear_sql'] = [clear_sql, target_connect]

                templet = ','.join([self.get_placeholder(target_type, i) for i, _ in enumerate(target_field_list)])
                exec_sql = "INSERT INTO {} ({}) VALUES ({})".format(target_table, target_field, templet)
                self.task_config[task_name]['exec_sql'] = [exec_sql, target_connect]
                self.log.debug("初始化插入语句：" + exec_sql)
            # 更新数据
            if mode in range(10, 15):
                templet = ','.join(["{}={}".format(key, self.get_placeholder(target_type, i)) for i, key in
                                    enumerate(target_field_list) if key != target_gid_field])
                exec_sql = "UPDATE {} SET {} WHERE {} IN ({})".format(target_table, templet, target_gid_field, '{}')
                self.task_config[task_name]['exec_sql'] = [exec_sql, target_connect]
                self.log.debug("初始化更新语句：" + exec_sql)
            # 删除数据
            if mode in range(15, 18):
                exec_sql = "DELETE FROM {} WHERE {} ={}".format(source_table, source_gid_field,
                                                                self.get_placeholder(source_type, 1))
                self.log.debug("初始化删除语句：" + exec_sql)
                self.task_config[task_name]['exec_sql'] = [exec_sql, source_connect]

            # 标记数据
            if flag_field:
                flag_end_value = "'{}'".format(flag_end_value) if source_type != 'access' else flag_end_value
                source_table = re.findall('JOIN\W+(\w+)', source_table)[0] if 'JOIN' in source_table else source_table
                flag_field = re.findall('\w+\.(\w+)', flag_field)[0] if '.' in flag_field else flag_field
                source_gid_field = re.findall('\w+\.(\w+)', source_gid_field)[
                    0] if '.' in source_gid_field else source_gid_field

                exec_sql = "UPDATE {} SET {}={} WHERE {}={}".format(source_table, flag_field, flag_end_value,
                                                                    source_gid_field,
                                                                    self.get_placeholder(source_type, 1))
                self.log.debug("初始化回写标记语句：" + exec_sql)
                self.task_config[task_name]['flag_sql'] = [exec_sql, source_connect]
            else:
                exec_sql = "UPDATE LastMark SET Mark='{}' WHERE TaskName='{}'".format('{}', task_name)
                self.log.debug("初始记录本地序号语句：" + exec_sql)
                self.task_config[task_name]['flag_sql'] = [exec_sql, self.local_connect]

    # 选择数据数量
    def get_select_count(self, sql, db_type, count = 10):
        if db_type in ('access', 'mssql', 'sql server', 'sqlserver'):
            return sql.replace('SELECT', 'SELECT TOP {}'.format(count))
        if db_type in ('mysql', 'sqlite'):
            return sql + " LIMIT {}".format(count)
        if db_type == 'oracle':
            return "SELECT * FROM ({}) WHERE ROWNUM<={}".format(sql, count)

    # 获取本地最后流水号
    def get_last_gid(self, task_name):
        sql = "SELECT * FROM LastMark WHERE TaskName='{}'".format(task_name)
        data = self.local_connect.loadSql(sql, True)
        if data == 0:
            sql = "INSERT INTO LastMark (Mark,UpdateTime,TaskName) VALUES (0,'{}','{}')".format(
                    timeEXT.get_datetime_str(), task_name)
            self.local_connect.execSql(sql)
            return 0
        else:
            return data[0].get('Mark', 0)

    # 获取点位符
    @staticmethod
    def get_placeholder(db_type, i = None):
        if db_type == "oracle":
            return ":{}".format(i)
        if db_type in ["sqlite", 'access']:
            return "?"
        if db_type in ("sqlserver", "mysql", "mssql", "sql server"):
            return "%s"

    # 连接手动查询语句
    def concat_manual_select(self, table_name, sql, other, datetime_field, db_type):
        other = ' AND {}'.format(other) if other else ''
        if db_type.lower() == 'access':
            ext = "{0}>#{1}# AND {0}<#{1}# ".format(datetime_field, '{}') + other
        elif db_type.lower() == 'mysql':
            ext = "{0}>{1} AND {0}<{1} ".format(datetime_field, timeEXT.str_to_mysql_datetime('{}')) + other
        elif db_type.lower() in ('sqlserver', 'sql server', 'mssql'):
            ext = "{0}>{1} AND {0}<{1} ".format(datetime_field, timeEXT.str_to_sqlserver_datetime('{}')) + other
        elif db_type.lower() == "oracle":
            ext = "{0}>{1} AND {0}<{1} ".format(datetime_field, timeEXT.str_to_oracle_datetime('{}')) + other
        else:
            ext = "{0}>'{1}' AND {0}<'{1}' ".format(datetime_field, '{}') + other
        if 'WHERE' in sql:
            sql = sql.replace('WHERE', " WHERE {} AND".format(ext))
            return sql
        else:
            sql = sql.replace(table_name, "{} WHERE {} ".format(table_name, ext))
            return sql

    # 获取任务配置字段列表
    def get_field(self, data):
        source_field_list = []
        target_field_list = []
        name_list = []
        for row in data:
            values = [row[key] for key in ['Description', 'FieldName', 'DefaultValue', 'TargetField']]
            name, source_field, default_value, target_field = values
            if not source_field and not default_value:
                continue
            if default_value:
                default_value = "'%s'" % default_value
            source_field = source_field or default_value
            name_list.append(name)
            source_field_list.append(source_field)
            target_field_list.append(target_field)
        return name_list, source_field_list, target_field_list

    # 获取字段配置
    def get_field_config(self, source_table, target_table, mode):
        sql = "SELECT * FROM FieldConfig WHERE TableName='{}' AND TargetTable='{}' AND Mode='{}' ORDER BY ID".format(
                source_table, target_table, mode)
        return self.local_connect.loadSql(sql, True)

    # 获取字段类型
    def get_field_info(self, conn, table_name, target_field_list):
        if not conn:
            self.log.warning("数据库连接,失败,查询目的表:{},字段类型出错...")
            return
        db_type = conn.type
        # print(conn,conn.type,table_name,target_field_list)
        db_type = db_type.lower()
        if db_type == 'oracle':
            sql = "SELECT COLUMN_NAME,DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME='{}'".format(table_name)
        if db_type == 'mysql':
            sql = "SELECT column_name,data_type FROM information_schema.COLUMNS WHERE table_name='{}'".format(
                    table_name)
        if db_type in ('mssql', 'sql server', 'sqlserver'):
            sql = ("SELECT b.name field_name,c.name field_type FROM sysobjects a,syscolumns b,systypes c WHERE"
                   " a.id=b.id AND a.name='{}' AND b.xtype=c.xtype").format(table_name)

        data = conn.loadSql(sql)
        if not data:
            return
        type_dict = {row[0]: row[1] for row in data}
        type_list = [type_dict.get(key) or type_dict.get(key.upper()) for key in target_field_list]
        return type_list

    # 删除映射行数
    @pyqtSlot(bool)
    def on_delete_row_clicked(self):
        row_num = -1
        for i in self.ui.field_table.selectionModel().selection().indexes():
            row_num = i.row()
        if row_num == -1:
            row_num = self.ui.field_table.rowCount() - 1
        self.ui.field_table.removeRow(row_num)

    # 增加映射行
    @pyqtSlot(bool)
    def on_add_row_clicked(self):
        row_num = -1
        for i in self.ui.field_table.selectionModel().selection().indexes():
            row_num = i.row()
        if row_num == -1:
            row_num = self.ui.field_table.rowCount()
        self.ui.field_table.insertRow(row_num)

    # 加载任务映射配置
    def load_task_config(self, task_name = None):
        # 设置字段表宽
        wide_list = [40, 100, 400, 200, 120]
        _ = [self.ui.field_table.setColumnWidth(i, wide) for i, wide in enumerate(wide_list)]
        # 获取任务配置
        data = self.get_task_config(task_name)
        if not data:
            self.log.info("没有调度任务配置,如需要请在调度配置里设置....")
            return
        connect_list = [row.get('name') for row in self.get_connect_config()]
        self.ui.source_connect_list.addItems(connect_list)
        self.ui.target_connect_list.addItems(connect_list)
        for i, row in enumerate(data):
            task_name = row.get('Name')
            if '.py' in task_name.lower():  # todo 过滤脚本任务
                continue
            source_table_name, target_table_name, sql_type = task_name.split('>')
            self.set_task_field_group(task_name)
            self.set_table_list(source_table_name, target_table_name)
        # 源表名变化
        self.ui.source_table_list.currentIndexChanged.connect(self.source_table_changed)
        self.ui.source_table_list.activated.connect(self.source_table_changed)
        self.ui.source_table_list.editTextChanged.connect(self.source_table_changed)
        self.ui.sql_tpye.currentIndexChanged.connect(
                lambda: self.source_table_changed(self.ui.source_table_list.currentText()))

    # 源表名称变化
    def source_table_changed(self, source_table = None):
        if not source_table:
            source_table = self.ui.source_table_list.currentText()
        target_table = self.ui.target_table_list.currentText()
        sql_type = self.ui.sql_tpye.currentIndex()
        if not source_table or not target_table:
            # show_message("请确认源表和目的表均不为空.....")
            return
        # 设置任务条件字段显示
        task_name = "{}>{}>{}".format(source_table, target_table, sql_type)
        config = self.get_task_config(task_name)
        if not config:
            return
        config = config[0]
        self.ui.source_connect_list.setCurrentText(config.get('SourceConnectName'))
        self.ui.target_connect_list.setCurrentText(config.get('TagConnectName'))
        self.ui.sql_tpye.setCurrentIndex(int(config.get('Mode', 0)))
        self.ui.task_name.setText(config.get('Description'))
        self.ui.primary_key_field.setText(config.get('SerialField'))
        self.ui.flag_field.setText(config.get('MarkField'))
        self.ui.flag_begin_value.setText(config.get('MarkFieldInitValue'))
        self.ui.flag_end_value.setText(config.get('MarkFieldEndValue'))
        self.ui.datetime_field.setText(config.get('DateField'))
        self.ui.other_conditions.setText(config.get('Other'))
        # 显示字段信息
        obj = self.ui.field_table
        data = self.get_field_config(source_table, target_table, sql_type)
        if not data:
            obj.setRowCount(0)
            return
        obj.setRowCount(0)
        obj.setRowCount(len(data))
        for i, row in enumerate(data):
            sn = row.get('ID')
            field_name = row.get('Description')
            default_value = row.get('DefaultValue')
            source_field = row.get('FieldName')
            target_field = row.get('TargetField')
            values = [sn, field_name, source_field, default_value, target_field]
            _ = [obj.setItem(i, col, QTableWidgetItem(str(field))) for col, field in enumerate(values)]

    # 设置表名列表
    def set_table_list(self, source_table_name, target_table_name):
        obj = self.ui.source_table_list
        row = [obj.itemText(i) for i in range(obj.count()) if obj.itemText(i) == source_table_name]
        if not row:
            obj.addItem(source_table_name)
        obj = self.ui.target_table_list
        row = [obj.itemText(i) for i in range(obj.count()) if obj.itemText(i) == target_table_name]
        if not row:
            obj.addItem(target_table_name)

    # 设置映射组
    def set_task_field_group(self, task_name):
        obj = self.ui.task_field_group
        row = [obj.itemText(i) for i in range(obj.count()) if obj.itemText(i) == task_name]
        if not row:
            obj.addItem(task_name)
            # self.task_config.update({task_name: data})

    # 获取连接配置
    def get_connect_config(self):
        data = self.local_connect.loadSql("SELECT * FROM ConnectConfig ", 1)
        return data

    # 获取任务配置
    def get_task_config(self, name = None):
        if name:
            sql = "SELECT * FROM SchedulerConfig WHERE Name='{}'".format(name)
        else:
            sql = "SELECT * FROM SchedulerConfig"
        data = self.local_connect.loadSql(sql, True)
        return data

    # 选择的表组件
    def select_table_name(self, obj, index):
        if obj and isinstance(index, int):
            self.select_table = [obj, index]

    # 删除表名
    @pyqtSlot(bool)
    def on_delete_task_table_name_clicked(self):
        if not self.select_table:
            show_message("请先选择要删除的是源表或目的表....")
            return
        index = self.select_table[1]
        table_name = self.select_table[0].currentText()
        obj_name = "目的表:{} ???" if self.select_table[0].objectName() == "target_table_list" else "源表:{} ???"
        table_type = "目的" if self.select_table[0].objectName() == "target_table_list" else "源"

        result = show_message("是否删除,{},".format(obj_name.format(table_name)))
        if not result:
            return

        sql = "SELECT TableName FROM FieldConfig WHERE TableName='{}' GROUP BY TargetTable".format(table_name)
        data = self.local_connect.loadSql(sql)
        if data and len(data) >= 2:
            self.show_message("不能删除表:{},还有其它任务引用此表".format(table_name))
            return
        sql = "DELETE FROM TableConfig WHERE TableName='{}' AND TagSource='{}'".format(table_name, table_type)
        if self.local_connect.execSql(sql):
            self.select_table[0].removeItem(index)
            self.select_table = None

    # 删除映射及任务配置
    @pyqtSlot(bool)
    def on_delete_task_field_group_clicked(self, task_name = None):
        if not task_name:
            task_name = self.ui.task_field_group.currentText()
        if not show_message("是否确认删除任务: {} 映射数据 ?".format(task_name)):
            return

        if not task_name:
            show_message("没有映射组数据")
            return
        source_table, target_table, mode = task_name.split('>')
        sql = "DELETE FROM FieldConfig WHERE TableName='{}' AND TargetTable='{}' AND Mode='{}' ".format(
                *task_name.split('>'))
        result = self.local_connect.execSql(sql)
        self.log.warning("删除映射组:{},字段配置:{}条".format(task_name, result))
        sql = "DELETE FROM SchedulerConfig WHERE Name ='{}' AND Mode='{}'".format(task_name, mode)
        result = self.local_connect.execSql(sql)
        self.log.warning("删除映射组:{},任务配置:{}条".format(task_name, result))
        self.ui.task_field_group.removeItem(self.ui.task_field_group.currentIndex())
        return True

    # 修改映射数据
    @pyqtSlot(bool)
    def on_modify_task_field_group_clicked(self):
        task_name = self.ui.task_field_group.currentText()
        old_task_name = task_name.split('>')
        new_source_table = self.ui.source_table_list.currentText()
        new_target_table = self.ui.target_table_list.currentText()
        new_mode = self.ui.sql_tpye.currentIndex()
        old_task_name.append(new_source_table)
        old_task_name.append(new_target_table)
        old_task_name.append(new_mode)
        info = "是否确认修改，{0}={3}，{1}={4}，{2}={5}".format(*old_task_name)
        if not show_message(info):
            return
        new_task_name = "{}>{}>{}".format(new_source_table, new_target_table, new_mode)
        # 修改任务
        sql = "UPDATE SchedulerConfig SET Name ='{}',Mode='{}' WHERE Name='{}' AND Mode='{}'".format(new_task_name,
                                                                                                     new_mode,
                                                                                                     task_name,
                                                                                                     old_task_name[2])
        result = self.local_connect.execSql(sql)
        if result:
            self.log.info("修改调度任务成功:{}".format(sql))
        # 修改映射
        sql = ("UPDATE FieldConfig SET TableName='{}',TargetTable='{}',Mode='{}' WHERE"
               " TableName='{}' AND TargetTable='{}' AND Mode='{}'"
               ).format(new_source_table, new_target_table, new_mode, *old_task_name)
        result = self.local_connect.execSql(sql)
        if result:
            self.log.info("修改映射组成功:{}".format(sql))
            self.ui.task_field_group.removeItem(self.ui.task_field_group.currentIndex())
            self.ui.task_field_group.addItem(new_task_name)
            data = self.get_task_config(new_task_name)
            if not data:
                return
            self.set_task_field_group(new_task_name)
            self.ui.task_field_group.setCurrentText(new_task_name)

    # 显示映射数据
    @pyqtSlot(str)
    def on_task_field_group_currentTextChanged(self, task_name):

        if not task_name or (task_name and len(task_name) < 6):
            self.log.warning("检测任务名称:{},不是一个有效名".format(task_name))
            return
        (source_table, target_table, mode) = task_name.split('>')
        self.ui.sql_tpye.setCurrentIndex(int(mode))
        self.ui.target_table_list.setCurrentText(target_table)
        self.ui.source_table_list.setCurrentText(source_table)

    # 重写关闭事件
    def closeEvent(self, event):
        if show_message("如果配置改变重启程序才能生效，是否退出程序?"):
            os._exit(0)
        else:
            self.hide()

    # 存储及增加任务
    @pyqtSlot(bool)
    def on_save_task_clicked(self):
        target_table = self.ui.target_table_list.currentText()
        if target_table not in [self.ui.target_table_list.itemText(i) for i in
                                range(self.ui.target_table_list.count())]:
            self.ui.target_table_list.addItem(target_table)
        source_table = self.ui.source_table_list.currentText()
        if source_table not in [self.ui.source_table_list.itemText(i) for i in
                                range(self.ui.source_table_list.count())]:
            self.ui.source_table_list.addItem(source_table)
        mode = self.ui.sql_tpye.currentIndex()
        primary_key_field = self.ui.primary_key_field.text().replace("'", "''") or ''
        if not primary_key_field:
            show_message("主键/流水字段,必须设置...")
            return
        flag_field = self.ui.flag_field.text() or ''
        other_conditions = self.ui.other_conditions.text().replace("'", "''") or ''
        flag_begin_value = self.ui.flag_begin_value.text() or ''
        flag_end_value = self.ui.flag_end_value.text() or ''
        datetime_field = self.ui.datetime_field.text().replace("'", "''")
        task_name = "{}>{}>{}".format(source_table, target_table, mode)
        if self.ui.field_table.rowCount() <= 0:
            show_message("没有映射的字段，请先增加映射数据")
            return
        name = self.ui.task_name.text()
        source_connect_name = self.ui.source_connect_list.currentText()
        target_connect_name = self.ui.target_connect_list.currentText()
        data = self.get_task_config(task_name)
        if data:
            sql = ("UPDATE SchedulerConfig SET Description='{}', TagConnectName='{}', SourceConnectName='{}',"
                   " Other='{}',DateField='{}', Mode={} ,SerialField='{}',MarkField='{}',MarkFieldInitValue='{}',"
                   "MarkFieldEndValue='{}' WHERE Name='{}';"
                   ).format(name, target_connect_name, source_connect_name, other_conditions, datetime_field, mode,
                            primary_key_field, flag_field, flag_begin_value, flag_end_value, task_name)
        else:
            cycle = randint(3, 30)
            sql = ("INSERT INTO SchedulerConfig (Description,Name,Cycle,AutoStart,Start,Stop,TagConnectName,"
                   "SourceConnectName,SerialField,MarkField,MarkFieldInitValue,MarkFieldEndValue,Other,DateField,Mode)"
                   " VALUES ('{}','{}','{}',0,0,2,'{}','{}','{}','{}','{}','{}','{}','{}','{}')").format(
                    name, task_name, cycle, target_connect_name, source_connect_name, primary_key_field, flag_field,
                    flag_begin_value, flag_end_value, other_conditions, datetime_field, mode)
        self.log.info("sql=" + sql)
        result = self.local_connect.execSql(sql)
        show_message("增加/修改任务：{}，成功".format(task_name))
        data = self.get_task_config(task_name)
        if data:
            self.set_task_field_group(task_name)
        if result:
            self.save_field(task_name)

    # 存储字段
    def save_field(self, task_name):
        sql = "DELETE FROM FieldConfig WHERE TableName='{}' and TargetTable='{}' AND Mode='{}'".format(
                *task_name.split('>'))
        self.local_connect.execSql(sql)
        obj = self.ui.field_table
        rows = obj.rowCount()
        cols = obj.columnCount()
        source_table = self.ui.source_table_list.currentText()
        target_table = self.ui.target_table_list.currentText()
        mode = self.ui.sql_tpye.currentIndex()

        gid = self.ui.primary_key_field.text()
        if gid not in [obj.item(i, 2).text() for i in range(rows)]:
            info = "主键或流水字段: {} ,未在字段映射配置找到,不能保存映射配置，请修改映射。。。,".format(gid)
            show_message(info)
            self.log.warning(info)
            return

        values = [[obj.item(i, col).text() if obj.item(i, col) else '' for col in range(cols)] for i in range(rows)]
        sql = ("INSERT INTO FieldConfig(ID,Description,FieldName,DefaultValue,TargetField,TableName,TargetTable,Mode)"
               " VALUES (?,?,?,?,?,'{}','{}','{}');".format(source_table, target_table, mode))
        result = self.local_connect.execSql(sql, values)
        self.log.info("存储任务：{}>{}，字段映射：{}个，成功".format(source_table, target_table, result))


if __name__ == '__main__':
    # import localDB

    log = loadLog.Logger(name = 'main')
    config = {'databasepath': './app/config.db', 'type': 'sqlite'}
    print(os.path.abspath(config.get('databasepath')))
    conn = connect_database.Connect(**config)
    app = QApplication(sys.argv)
    gui = Window(conn)
    gui.show()
    sys.exit(app.exec_())